package fun.sssdnsy.media.image;

import javafx.beans.binding.DoubleBinding;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.effect.Glow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.stage.Stage;


public class ResizableImageView extends ImageView {
    private static final double INITIAL_SCALE_FACTOR = 0.5;
    private final ObjectProperty<Boolean> selected = new SimpleObjectProperty<>(false);
    private final DoubleProperty scale = new SimpleDoubleProperty(1.0);

    public ResizableImageView(Image image,DoubleBinding width,DoubleBinding height) {
        super(image);
        initScaling(width, height);
        initSelectionHandler();
        initWheelHandler();
    }

    private void initSelectionHandler() {
        // 鼠标点击选中/取消选中
        setOnMouseClicked(e -> {
            if (e.getButton() == MouseButton.PRIMARY) {
                setSelected(!isSelected());
                e.consume();
            }
        });

        // 选中状态可视化
        selected.addListener((obs, oldVal, newVal) -> {
            if (newVal) {
                setEffect(new Glow(0.3));
                setStyle("-fx-border-color: #2196F3; -fx-border-width: 2;");
            } else {
                setEffect(null);
                setStyle("");
            }
        });
    }

    public boolean isSelected() {
        return selected.get();
    }

    public void setSelected(boolean selected) {
        this.selected.set(selected);
    }

    private void initWheelHandler() {
        setOnScroll(e -> {
            if (isSelected() && e.isControlDown()) {
                double delta = e.getDeltaY() > 0 ? 1.1 : 0.9;
                scale.set(scale.get() * delta);

                // 限制缩放范围（0.2倍 - 5倍）
                if (scale.get() < 0.2) scale.set(0.2);
                if (scale.get() > 5.0) scale.set(5.0);

                e.consume();
            }
        });
    }


    private void initScaling( DoubleBinding width, DoubleBinding height) {
        // 初始缩放为窗口一半大小
        fitWidthProperty().bind(width);
        fitHeightProperty().bind(height);
        setPreserveRatio(true);

        // 动态调整保持比例
        scale.addListener((obs, oldVal, newVal) -> {
            setFitWidth(getImage().getWidth() * newVal.doubleValue());
            setFitHeight(getImage().getHeight() * newVal.doubleValue());
        });
    }
}
